#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../include/utils.h"

int Hex2Char(unsigned int fromi,unsigned char *toc)
{
    if(fromi >= 0 && fromi <= 9){
        *toc = 0x30 + fromi;
        return SUCCESS;
    }else if(fromi >= 10 && fromi <= 15){
        *toc = 0x41 + fromi - 10;
        return SUCCESS;
    }
    return ERROR;
}

int Char2Hex(unsigned char fromc,unsigned int *toi)
{
    if(fromc >= 0x30 && fromc <=0x39){
        *toi = fromc - 0x30;
        return SUCCESS;
    }else if(fromc >= 0x41 && fromc <= 0x46){
        *toi = fromc -0x41 + 10;
        return SUCCESS;
    }
    return ERROR;
}

int Bitstr2ByteArr(unsigned char *bs, unsigned char *ba)
{
    if((int)strlen(bs) % 8 ==0 && (int)strlen(bs) <= 32) {
        for(int i = 0; i < (int)strlen(bs); i += 8){
            int sum1 = (bs[i] - 0x30) * 8 + (bs[i+1] - 0x30) * 4 + (bs[i+2] - 0x30) * 2 + (bs[i+3] - 0x30);
            int sum2 = (bs[i+4] - 0x30) * 8 + (bs[i+5] - 0x30) * 4 + (bs[i+6] - 0x30) * 2 + (bs[i+7] - 0x30);
            char temp1 = (char)sum1;
            char temp2 = (char)sum2;
            char final = (temp1 << 4) | temp2;
            // printf("%c", final);
            ba[i/8] = final;
        }
        return SUCCESS;
    }
    return ERROR;
}

int ByteArr2Bitstr(unsigned char *ba, unsigned char *bs)
{
    if((int)strlen(ba) <=4){
        char *array[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};
        int i;
        for(i = 0; i < (int)strlen(ba); i++){
            char temp1 = ba[i];
            char temp2 = (temp1 >> 4) & 0x000f;
            char temp3 = temp1 & 0x000f;
            
            if(temp2 >= 0x00 && temp2 <= 0x09){
                // printf("%s\n", array[temp2 - 0x00]);
                strcpy(bs + i*8, array[temp2 - 0x00]);
            }else if(temp2 >= 0x0a && temp2 <= 0x0f){
                // printf("%s\n", array[temp2 - 0x0a + 10]);
                strcpy(bs + i*8, array[temp2 - 0x0a + 10]);
            }
            if(temp3 >= 0x00 && temp3 <= 0x09){
                // printf("%s\n", array[temp3 - 0x00]);
                strcpy(bs + i*8 + 4, array[temp3 - 0x00]);
            }else if(temp3 >= 0x0a && temp3 <= 0x0f){
                // printf("%s\n", array[temp3 - 0x0a + 10]);
                strcpy(bs + i*8 + 4, array[temp3 - 0x0a + 10]);
            }
        }
        return SUCCESS;
    }
    return ERROR;
}
